var money;
var highestBet;
var timer;
function setTimeCount() {
	
	refreshSeats();
	timer = setTimeout("setTimeCount()", 500);
	
}

function validateNewPlayer( username ) {
	if(!username || username.length == 0) {
		showWarning("Enter Player Name");
		return false;
	}
	else if(username.length > 10) {
		showWarning("Player Name should not be more than 10 characters");
		return false;
	}
	else {
		return true;
	}
}

function showWarning( stringWarning ) {
	alert( stringWarning );
}

function trim( string ) {
	return string.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function validateSeat( seatNumber ) {
	var username = document.getElementById('nameField'+seatNumber).value;
	username = trim(username);
	if(validateNewPlayer(username)==true) {
		occupySeat(seatNumber, username);
	}
}

function getXMLHTTPObject(){
	var xmlhttp;
	try {// Opera 8.0+, Firefox, Safari
		xmlhttp = new XMLHttpRequest();
	}
	catch (e) {
		try {// Internet Explorer Browsers
			xmlhttp = new ActiveXObject( 'Msxml2.XMLHTTP' );
		}
		catch (e) {
			try {
				xmlhttp = new ActiveXObject( 'Microsoft.XMLHTTP' );
			}
			catch (e) {// Something went wrong
				alert( "Your browser must support AJAX" );
				return false;
			}
		}
	}
	return xmlhttp;
}

function disableButtons() {
	var sitButton = document.getElementsByName("sitButton");
	for(var x=0; x<sitButton.length; x++) 
		sitButton.item(x).disabled = true;
}


function occupySeat( seatNumber, username  ){
	var xmlhttp = getXMLHTTPObject();
	xmlhttp.onreadystatechange = function(){
		if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
			document.getElementById("seat" + playerNumber).innerHTML = unescape(xmlhttp.responseText);
	};
	xmlhttp.open( 'POST', "testCreation", true );
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send( "seatNumber=" + seatNumber + "&playerName=" + username );
}


function refreshSeats(){
	var xmlhttp = getXMLHTTPObject();
	
	xmlhttp.onreadystatechange = function(){
		if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
			
			var xmlDoc = xmlhttp.responseXML;
			var playerTypes  = xmlDoc.getElementsByTagName("type");
			var playerNames  = xmlDoc.getElementsByTagName("name");
			var playerBlinds  = xmlDoc.getElementsByTagName("blinds");
			var playerMoneys  = xmlDoc.getElementsByTagName("money");
			var playerBets = xmlDoc.getElementsByTagName("bet");
			var playerCards1 = xmlDoc.getElementsByTagName("card1");
			var playerCards2 = xmlDoc.getElementsByTagName("card2");
			var playerIsTurns = xmlDoc.getElementsByTagName("isTurn");
			var playerHasFoldeds = xmlDoc.getElementsByTagName("hasFolded");
			var playerCount = xmlDoc.getElementsByTagName("playerCount");
				playerCount = playerCount[0].childNodes[0].nodeValue;
			var showdown = xmlDoc.getElementsByTagName("showdown")[0].childNodes[0].nodeValue;
			var ended = xmlDoc.getElementsByTagName("ended")[0].childNodes[0].nodeValue;
				
			var playerType;
			var playerName;
			var playerBlind;
			var playerMoney;
			var playerBet;
			var playerCard1;
			var playerCard2;
			var isTurn;
			var hasFolded;


			
			var gameStatus = xmlDoc.getElementsByTagName("gameStatus");
				gameStatus = gameStatus[0].childNodes[0].nodeValue;
				
			if(gameStatus=="true" && showdown=="false" && ended=="false"){
				document.getElementById("startButton").innerHTML = "<h3>Game Started</h3>";
				var potValue = xmlDoc.getElementsByTagName("pot")[0].childNodes[0].nodeValue;
				var lastBetValue = xmlDoc.getElementsByTagName("lastBet")[0].childNodes[0].nodeValue;
				highestBet = parseInt(lastBetValue);
				document.getElementById("pot").innerHTML = potValue;
				document.getElementById("lastBet").innerHTML = lastBetValue;
				
				disableButtons();
			}
			
			for(var x=0; x<9; x++){
				playerBlind = playerBlinds[x].childNodes[0].nodeValue;
				playerType = playerTypes[x].childNodes[0].nodeValue;
				playerType = parseInt(playerType);
				playerName = playerNames[x].childNodes[0].nodeValue;
				playerMoney = playerMoneys[x].childNodes[0].nodeValue;
				playerBet = playerBets[x].childNodes[0].nodeValue;
				playerCard1 = playerCards1[x].childNodes[0].nodeValue;
				playerCard2 = playerCards2[x].childNodes[0].nodeValue;
				isTurn = playerIsTurns[x].childNodes[0].nodeValue;
				hasFolded = playerHasFoldeds[x].childNodes[0].nodeValue;
				
				if(isTurn=="true") {
					document.getElementById("seat" + x).style.backgroundColor = "#B8C4E0";
					document.getElementById("seat" + x).style.boxShadow = "inset 10px -10px 50px 5px #94A6D1";
				}
				else {
					document.getElementById("seat" + x).style.backgroundColor = "#DBDBDB";
					document.getElementById("seat" + x).style.boxShadow = "inset 10px -10px 50px 5px #C2C2C2";
				}
				
				if(hasFolded=="true") {
					document.getElementById("seat" + x).style.backgroundColor = "#A3A3A3";
					document.getElementById("seat" + x).style.boxShadow = "inset 10px -10px 50px 5px #575757";
					document.getElementById("seat" + x).getElementsByTagName("img")[0].style.visibility = "hidden";
					document.getElementById("seat" + x).getElementsByTagName("img")[1].style.visibility = "hidden";
				}
				
				if(playerType==0) {
					if(!document.getElementById("nameField"+x)) {
						document.getElementById("seat"+x).innerHTML = "<input class=\"textfield\" placeholder=\"Player Name" + x + "\" id =\"nameField" + x + "\" type=\"text\">" + 
																	  "<input type=\"button\" value=\"Sit Here\" onclick=\"validateSeat('" + x + "')\" name=\"sitButton\">";
					}
				}
				
				else {
					document.getElementById("bet"+x).innerHTML = "bet:<br />" + playerBet;
					if(!document.getElementById(x + "name")) {
						document.getElementById("seat" + x).innerHTML = 
							"<div id='"+x+"name'>Name: " + playerName + "</div>" +
							"<div id='"+x+"blindStatus'>Status: " + playerBlind + "</div>" +
							"<div id='"+x+"money'>Money: " + playerMoney + "</div>" +
							"<img class='cardLeft' src='media/images/Blank.png' />" + "<img class='cardRight' src='media/images/Blank.png' />";
					}
					else {
						document.getElementById(x+"blindStatus").innerHTML = "Status: " + playerBlind;
						document.getElementById(x+"money").innerHTML = "Money: " + playerMoney;
						
						if(playerType==1) {
							if(ended=="false") {
								document.getElementById("seat" + x).getElementsByTagName("img")[0].src = "media/images/FaceDown.png";
								document.getElementById("seat" + x).getElementsByTagName("img")[1].src = "media/images/FaceDown.png";
							}
							else {
								document.getElementById("seat" + x).getElementsByTagName("img")[0].src = "media/images/" + playerCard1;
								document.getElementById("seat" + x).getElementsByTagName("img")[1].src = "media/images/" + playerCard2;
							}
						}
						
						else if(playerType==2) {
							document.getElementById("seat" + x).getElementsByTagName("img")[0].src = "media/images/" + playerCard1;
							document.getElementById("seat" + x).getElementsByTagName("img")[1].src = "media/images/" + playerCard2;
							disableButtons();
							money = parseInt(playerMoney);
							
							if(playerCount>=3&&gameStatus=="false")
								document.getElementById("startButton").innerHTML = "<input type='button' value = 'Start Game' onClick ='invokeServlet(\"startGame\")'/>";
							
							
							if(isTurn=="true")
								displayButtons(xmlDoc);
							else
								removeButtons();
							
							
						}
						
						//Display Showdown Button
						if(showdown=="true" && ended=="false") {
							document.getElementById("startButton").innerHTML = "<input type='button' value='SHOWDOWN' onClick='showdown()' />";
						}
						//Display New Round Button
						if(showdown=="false" && ended=="true")
							document.getElementById("startButton").innerHTML = "<input type='button' value='new round' onClick='invokeServlet(\"newRound\")'/>"
					}
				}	
			}

			var roundCardCount =  xmlDoc.getElementsByTagName("roundCardCount");
			roundCardCount = roundCardCount[0].childNodes[0].nodeValue;
			roundCardCount = parseInt(roundCardCount);
			var roundCards = xmlDoc.getElementsByTagName("roundCards");
			var roundCard;

			for(var i=0; i<roundCardCount; i++){
				roundCard = roundCards[i].childNodes[0].nodeValue;
				document.getElementById("roundCard" + i).src = "media/images/" + roundCard;
			}	
		}
	};
	
	xmlhttp.open( 'POST', 'refreshSeats', true );
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send( null );
}

function hideRaiseField(){
	document.getElementById("inputRaise").style.visibility = "hidden";
	document.getElementById("buttonOptions").style.visibility = "visible";
}

function verifyRaise() {
	var raiseAmount = parseInt(document.getElementById("raiseValue").value);
	if(isNaN(raiseAmount)) {
		alert("Numbers Only");
		return false;		
	}
	else if(raiseAmount+highestBet > money) {
		alert("Insufficient Funds");
		return false;
	}
	else if(raiseAmount<0) {
		alert("Only Positive Values");
		return false;
	}
	else
		return true;
}

function raise(){
	if(verifyRaise()) {
		
		hideRaiseField();		
		var raiseAmount = document.getElementById("raiseValue").value;
		document.getElementById("raiseValue").value = "";
	
		var xmlhttp = getXMLHTTPObject();
		xmlhttp.onreadystatechange = function(){
			if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
				
			}
		};
		xmlhttp.open( 'POST', "raiseAction", true );
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlhttp.send( "raiseAmount=" + raiseAmount);
	}
	else {
		document.getElementById("raiseValue").value = "";
	}
}

function showdown() {
	var xmlhttp = getXMLHTTPObject();
	xmlhttp.onreadystatechange = function(){
		if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
			document.getElementById("winnerMessage").innerHTML = xmlhttp.responseText;
		}
	};
	xmlhttp.open( 'POST', "rankHands", true );
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send(null);
}

function displayButtons(xmlDoc){
	var canAct = xmlDoc.getElementsByTagName("canAct");
	var canFold = canAct[0].childNodes[0].nodeValue;
	var canCall = canAct[1].childNodes[0].nodeValue;
	var canCheck = canAct[2].childNodes[0].nodeValue;
	var canRaise = canAct[3].childNodes[0].nodeValue;
	
	removeButtons();
	
	if(canCheck=="true")
		document.getElementById("checkBox").innerHTML = "<input type='button' value = 'Check' onClick ='invokeServlet(\"checkAction\")'/>";
	if(canCall=="true")
		document.getElementById("callBox").innerHTML = "<input type='button' value = 'Call' onClick ='invokeServlet(\"callAction\")'/>";
	if(canRaise=="true")
		document.getElementById("raiseBox").innerHTML = "<input type='button' value = 'Raise' onClick ='inputRaise()'/>";
	if(canFold=="true")
		document.getElementById("foldBox").innerHTML = "<input type='button' value = 'Fold' onClick ='invokeServlet(\"foldAction\")'/>";
}

function inputRaise() {
	document.getElementById("inputRaise").style.visibility = "visible";
	document.getElementById("buttonOptions").style.visibility = "hidden";
}

function removeButtons(){
	document.getElementById("checkBox").innerHTML = "";
	document.getElementById("callBox").innerHTML = "";
	document.getElementById("raiseBox").innerHTML = "";
	document.getElementById("foldBox").innerHTML = "";
}


function invokeServlet(servletURL) {
	var xmlhttp = getXMLHTTPObject();
	xmlhttp.open( 'POST', servletURL, true );
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlhttp.send( null );
	if(servletURL=="startGame")
		invokeServlet("newRound");
}

